//
//  DownLoadHelper.m
//  MISCloud
//
//  Created by goldeney on 13-9-18.
//  Copyright (c) 2013年 goldeneye. All rights reserved.
//

#import "DownLoadHelper.h"
#import "WebGetUserInfoToHttp.h"

@implementation DownLoadHelper
@synthesize downinglist=_downinglist;
@synthesize downloadDelegate=_downloadDelegate;
@synthesize finishedlist=_finishedList;
@synthesize request = _request;

#pragma mark - Public
static DownLoadHelper* sharedSingleton = nil;

+ (instancetype)sharedInstance
{
    @synchronized (self){
        if (sharedSingleton == nil)
        sharedSingleton = [[self alloc] initWithData];
    }
    return sharedSingleton;
}

- (id) initWithData
{
    [self loadFinishedfiles];
    [self loadTempfiles];
    
    return [super init];
}

-(NSData*)getPostData
{
    //传递用户信息
    NSMutableString *body = [[NSMutableString alloc] initWithCapacity:0];
    NSString *sessionValue = [WebGetUserInfoToHttp getUserInfoToJSON];
    [body appendFormat:@"session=%@&",sessionValue];
    
    //删除多余的“&”字符
    if(body.length>0) [body deleteCharactersInRange:NSMakeRange(body.length - 1, 1)];
    return [body dataUsingEncoding:NSUTF8StringEncoding];
}

//字典转Json
- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

-(void)beginRequest:(FileAttributeModel *)fileInfo isBeginDown:(BOOL)isBeginDown
{
    //如果不存在则创建临时存储目录
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSError *error;
    if(![fileManager fileExistsAtPath:[FilePathHelper getTempFolderPath]])
    {
        [fileManager createDirectoryAtPath:[FilePathHelper getTempFolderPath] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    //文件开始下载时，把文件名、文件总大小、文件URL写入文件，"上海滩.rtf"中间用逗号隔开
    NSString *writeMsg=[fileInfo.fileName stringByAppendingFormat:@",%@,%@,%d",
                        fileInfo.fileSize,fileInfo.fileURL,fileInfo.isExternalDown];
    NSInteger index=[fileInfo.fileName rangeOfString:@"."].location;
    NSString *name=[fileInfo.fileName substringToIndex:index];
    [writeMsg writeToFile:[[FilePathHelper getTempFolderPath]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.rtf",name]] atomically:YES encoding:NSUTF8StringEncoding error:&error];
    
    
    //按照获取的文件名获取临时文件的大小，即已下载的大小
    fileInfo.isFistReceived=YES;
    NSData *fileData=[fileManager contentsAtPath:[[FilePathHelper getTempFolderPath]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.temp",fileInfo.fileName]]];
    NSInteger receivedDataLength=[fileData length];
    fileInfo.fileReceivedSize=[NSString stringWithFormat:@"%ld",(long)receivedDataLength];
    
    //如果文件重复下载或暂停、继续，则把队列中的请求删除，重新添加
    for(ASIHTTPRequest *tempRequest in self.downinglist)
    {
        FileAttributeModel *oldFileInfo=[tempRequest.userInfo objectForKey:@"File"];
        if([oldFileInfo.fileURL isEqual:fileInfo.fileURL])
        {
            [tempRequest cancel];
            [tempRequest clearDelegatesAndCancel];
            [self.downinglist removeObject:tempRequest];
            break;
        }
    }
    
    if (fileInfo.isExternalDown) {
        _request=[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:fileInfo.fileURL]];
    } else {
        _request=[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:fileInfo.fileURL]];
        [_request setRequestMethod:@"POST"];
        NSMutableData *postData = [NSMutableData dataWithData:[self getPostData]];
        [_request setPostBody:postData];
    }
    
    [_request setDefaultResponseEncoding:NSUTF8StringEncoding];
    [_request setAllowCompressedResponse:NO];
    [_request addRequestHeader:@"Accept-Language" value:@"zh-CN"];
    [_request addRequestHeader:@"Charset" value:@"UTF-8"];
    [_request addRequestHeader:@"Connection" value:@"Keep-Alive"];
    
    _request.delegate=self;
    [_request setDownloadDestinationPath:[[FilePathHelper getTargetFloderPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileInfo.fileName]]];
    [_request setTemporaryFileDownloadPath:[[FilePathHelper getTempFolderPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.temp",fileInfo.fileName]]];
    [_request setDownloadProgressDelegate:self];
//    [request setDownloadProgressDelegate:downCell.progress];//设置进度条的代理,这里由于下载是在AppDelegate里进行的全局下载，所以没有使用自带的进度条委托，这里自己设置了一个委托，用于更新UI
    [_request setAllowResumeForFileDownloads:YES];//支持断点续传
    if(isBeginDown)
    {
        fileInfo.isDownloading=YES;
    }
    else
    {
        fileInfo.isDownloading=NO;
    }
    [_request setUserInfo:[NSDictionary dictionaryWithObject:fileInfo forKey:@"File"]];//设置上下文的文件基本信息
    [_request setTimeOutSeconds:30.0f];
    if (isBeginDown) {
        [_request startAsynchronous];
    }
    [self.downinglist addObject:_request];
}

-(void)cancelRequest:(ASIHTTPRequest *)request
{
    
}

-(void)loadTempfiles
{
    self.downinglist=[[NSMutableArray alloc] init];
    //如果不存在则创建临时存储目录
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSError *error;
    if(![fileManager fileExistsAtPath:[FilePathHelper getTempFolderPath]])
    {
        [fileManager createDirectoryAtPath:[FilePathHelper getTempFolderPath] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSArray *filelist=[fileManager contentsOfDirectoryAtPath:[FilePathHelper getTempFolderPath] error:&error];
    if(!error)
    {
        NSLog(@"%@",[error description]);
    }
    for(NSString *file in filelist)
    {
        if([file rangeOfString:@".rtf"].location<=100)//以.rtf结尾的文件是下载文件的配置文件，存在文件名称，文件总大小，文件下载URL
        {
            NSInteger index=[file rangeOfString:@"."].location;
            NSString *trueName=[file substringToIndex:index];
            
            //临时文件的配置文件的内容
            NSString *msg=[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:[[FilePathHelper getTempFolderPath]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.rtf",trueName]]] encoding:NSUTF8StringEncoding];
            
            NSArray *array = [msg componentsSeparatedByString:@","];
            //用于判断上一个版本数据大小不对称问题
            if (array && array.count>=4) {
                NSString *name = [array objectAtIndex:0];
                NSString *totalSize= [array objectAtIndex:1];
                NSString *url= [array objectAtIndex:2];
                BOOL isExternalDown= [[array objectAtIndex:3] boolValue];
                
                //按照获取的文件名获取临时文件的大小，即已下载的大小
                NSData *fileData=[fileManager contentsAtPath:[[FilePathHelper getTempFolderPath]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.temp",name]]];
                NSInteger receivedDataLength=[fileData length];
                
                //实例化新的文件对象，添加到下载的全局列表，但不开始下载
                FileAttributeModel *tempFile=[[FileAttributeModel alloc] init];
                tempFile.fileName=name;
                tempFile.fileSize=totalSize;
                tempFile.fileReceivedSize=[NSString stringWithFormat:@"%ld",(long)receivedDataLength];
                tempFile.fileURL=url;
                tempFile.isDownloading=NO;
                tempFile.isExternalDown = isExternalDown;
                [self beginRequest:tempFile isBeginDown:NO];
            }
            
        }
    }
}

-(void)loadFinishedfiles
{
    self.finishedlist=[[NSMutableArray alloc] init];
    
    //如果不存在则创建临时存储目录
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSError *error;
    if(![fileManager fileExistsAtPath:[FilePathHelper getTargetFloderPath]])
    {
        [fileManager createDirectoryAtPath:[FilePathHelper getTargetFloderPath] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSArray *filelist=[fileManager contentsOfDirectoryAtPath:[FilePathHelper getTargetFloderPath] error:&error];
    if(!error)
    {
        NSLog(@"%@",[error description]);
    }
    for(NSString *fileName in filelist)
    {
        if([fileName rangeOfString:@"."].location<100)//出去Temp文件夹
        {
            FileAttributeModel *finishedFile=[[FileAttributeModel alloc] init];
            finishedFile.fileName=fileName;
            
            //根据文件名获取文件的大小
            NSInteger length=[[fileManager contentsAtPath:[[FilePathHelper getTargetFloderPath] stringByAppendingPathComponent:fileName]] length];
            finishedFile.fileSize=[FileSizeFormatHelper getFileSizeString:[NSString stringWithFormat:@"%ld",(long)length]];
            
            [self.finishedlist addObject:finishedFile];
        }
    }
}

#pragma ASIHttpRequest回调委托

//出错了，如果是等待超时，则继续下载
-(void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error=[request error];
    NSLog(@"ASIHttpRequest出错了!%@",error);
    
    FileAttributeModel *fileInfo=(FileAttributeModel *)[request.userInfo objectForKey:@"File"];
    fileInfo.isDownloading = NO;
    
    if([self.downloadDelegate respondsToSelector:@selector(failedDownload:error:)]){
        [self.downloadDelegate failedDownload:request error:error];
    }
}

-(void)requestStarted:(ASIHTTPRequest *)request
{
    NSLog(@"开始了!");
    if([self.downloadDelegate respondsToSelector:@selector(startDownload:)])
        [self.downloadDelegate startDownload:request];
}

- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
    int statusCode = [request responseStatusCode];
    NSError *error=[request error];
    //如果发生错误，就返回空
    if (!error && statusCode == 200) {
        NSLog(@"收到回复了！");
        FileAttributeModel *fileInfo=[request.userInfo objectForKey:@"File"];
        fileInfo.fileSize=[FileSizeFormatHelper getFileSizeString:[responseHeaders objectForKey:@"Content-Length"]];
    }
}

////*********
//**注意：如果要要ASIHttpRequest自动断点续传，则不需要写上该方法，整个过程ASIHttpRequest会自动识别URL进行保存数据的
//如果设置了该方法，ASIHttpRequest则不会响应断点续传功能，需要自己手动写入接收到的数据，开始不明白原理，搞了很久才明白，如果本人理解不正确的话，请高人及时指点
//***********
//-(void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data
//{
//    FileAttributeModel *fileInfo=(FileAttributeModel *)[request.userInfo objectForKey:@"File"];
//    [fileInfo.fileReceivedData appendData:data];
//    fileInfo.fileReceivedSize=[NSString stringWithFormat:@"%d",[fileInfo.fileReceivedData length]];
//    [fileInfo.fileReceivedData writeToFile:request.temporaryFileDownloadPath atomically:NO];
//    NSString *configPath=[[CommonHelper getTempFolderPath] stringByAppendingPathComponent:[fileInfo.fileName stringByAppendingString:@".rtf"]];
//    NSString *tmpConfigMsg=[NSString stringWithFormat:@"%@,%@,%@,%@",fileInfo.fileName,fileInfo.fileSize,fileInfo.fileReceivedSize,fileInfo.fileURL];
//    NSError *error;
//    [tmpConfigMsg writeToFile:configPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
//    if(!error)
//    {
//        NSLog(@"错误%@",[error description]);
//    }
//    [self.downloadDelegate updateCellProgress:fileInfo];
//    NSLog(@"正在接受搜数据%d",[fileInfo.fileReceivedData length]);
//}

//1.实现ASIProgressDelegate委托，在此实现UI的进度条更新,这个方法必须要在设置[request setDownloadProgressDelegate:self];之后才会运行
//2.这里注意第一次返回的bytes是已经下载的长度，以后便是每次请求数据的大小
//费了好大劲才发现的，各位新手请注意此处
-(void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes
{
    FileAttributeModel *fileInfo=[request.userInfo objectForKey:@"File"];
    if(!fileInfo.isFistReceived)
    {
        fileInfo.fileReceivedSize=[NSString stringWithFormat:@"%lld",[fileInfo.fileReceivedSize longLongValue]+bytes];
    }
    if([self.downloadDelegate respondsToSelector:@selector(updateCellProgress:)])
    {
        [self.downloadDelegate updateCellProgress:request];
    }
    fileInfo.isFistReceived=NO;
}

//将正在下载的文件请求ASIHttpRequest从队列里移除，并将其配置文件删除掉,然后向已下载列表里添加该文件对象
-(void)requestFinished:(ASIHTTPRequest *)request
{
    int statusCode = [request responseStatusCode];
    NSLog(@"responseStatusCode：%d",statusCode);
    
    FileAttributeModel *fileInfo=(FileAttributeModel *)[request.userInfo objectForKey:@"File"];
    if (request.error) {
        fileInfo.isDownloading = NO;
        if([self.downloadDelegate respondsToSelector:@selector(failedDownload:error:)])
            [self.downloadDelegate failedDownload:request error:request.error];
        
        return;
    }
    
    //[self playDownloadSound];
    NSInteger index=[fileInfo.fileName rangeOfString:@"."].location;
    NSString *name=[fileInfo.fileName substringToIndex:index];;
    NSString *configPath=[[FilePathHelper getTempFolderPath] stringByAppendingPathComponent:[name stringByAppendingString:@".rtf"]];
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSError *error;
    //如果存在临时文件的配置文件
    if([fileManager fileExistsAtPath:configPath]) {
        [fileManager removeItemAtPath:configPath error:&error];
    }
    
    if(error) {
        NSLog(@"临时配置文件删除失败：%@",[error description]);
    }
    
    if([self.downloadDelegate respondsToSelector:@selector(finishedDownload:)]){
        [self.downloadDelegate finishedDownload:request];
    } else {
        [_downinglist removeObject:request];
        [_finishedList addObject:fileInfo];
    }
    
}


@end
